﻿using NewRen.Log4net;
using NewRen.Models;
using NewRen.Schemas;
using PagedList;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace NewRen.Areas.Admin.Controllers
{
    [Schema.LoginCheck]
    public class BbsController : BaseController
    {
        // GET: Admin/Bbs
        public ActionResult Index()
        {
            return View();
        }

        #region 板块管理
        /// <summary>
        /// 板块管理
        /// </summary>
        /// <param name="page"></param>
        /// <returns></returns>
        public ActionResult Forum(string key, DateTime? Begin, DateTime? End,int page = 1)
        {
            var query = db.Plates.AsEnumerable();
            if (!string.IsNullOrEmpty(key))
            {
                query = query.Where(p => p.Title.Contains(key));
            }
            if (Begin.HasValue)
            {
                query = query.Where(p => p.Time >= Begin);
            }
            if (End.HasValue)
            {
                query = query.Where(p => p.Time <= End);
            }
            var forums = query.OrderByDescending(p => p.Time).ToPagedList(page, 20);
            return View(forums);
        }

        /// <summary>
        /// 增加板块
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult AddForum()
        {
            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult AddForum(Plate model, HttpPostedFileBase file)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    if (file != null)
                    {
                        System.IO.Stream stream = file.InputStream;
                        byte[] buffer = new byte[stream.Length];
                        stream.Read(buffer, 0, (int)stream.Length);
                        stream.Close();
                        model.Picture = buffer;
                    }
                    model.Time = DateTime.Now;
                    model.Report = 0;
                    model.IsColse = false;
                    model.Browses = 0;
                    db.Plates.Add(model);
                    db.SaveChanges();
                    return Redirect("/Admin/Bbs/Forum");
                }
                catch
                {
                    ModelState.AddModelError("", "增加板块失败");
                }
            }
            else
            {
                ModelState.AddModelError("", "信息填写错误！");
            }
            return View();
        }

        /// <summary>
        /// 板块删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        [ValidateSID]
        public ActionResult ForumDelete(int id)
        {
            try
            {
                var forum = db.Plates.Find(id);
                var topics = db.Topics.Where(x => x.PlateID == forum.ID).ToList();
                foreach (Topic item in topics)
                {
                    db.Topics.Remove(item);
                }
                var collect = db.Collects.Where(x => x.TID == forum.ID).Where(x => x.CollectTypeAsInt == 2).ToList();
                foreach (Collect item in collect)
                {
                    db.Collects.Remove(item);
                }
                db.Plates.Remove(forum);
                db.SaveChanges();
                return Content("ok");
            }
            catch
            {
                return Content("err");
            }
        }

        [HttpGet]
        public ActionResult ForumEdit(int id)
        {
            var forum = db.Plates.Find(id);
            return View(forum);
        }

        /// <summary>
        ///  板块修改
        /// </summary>
        /// <param name="model"></param>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult ForumEdit(Plate model, HttpPostedFileBase file)
        {
            var _forum = db.Plates.Find(model.ID);
            if (ModelState.IsValid)
            {
                try
                {
                    var forum = db.Plates.Find(model.ID);
                    if (file != null)
                    {
                        System.IO.Stream stream = file.InputStream;
                        byte[] buffer = new byte[stream.Length];
                        stream.Read(buffer, 0, (int)stream.Length);
                        stream.Close();
                        forum.Picture = buffer;
                    }
                    forum.Title = model.Title;
                    forum.Description = model.Description;
                    forum.IsColse = model.IsColse;
                    var topics = db.Topics.Where(x => x.PlateID == model.ID).ToList();
                    foreach (Topic item in topics)
                    {
                        item.IsColse = model.IsColse;
                    }
                    db.SaveChanges();
                    return Redirect("/Admin/Bbs/Forum");
                }
                catch
                {
                    ModelState.AddModelError("", "修改板块失败！");
                }
            }
            else
            {
                ModelState.AddModelError("", "填写信息不正确！");
            }
            return View(_forum);
        }

        [HttpGet]
        public ActionResult ForumShow(int id)
        {
            var forum = db.Plates.Find(id);
            List<PlateOwner> owners = db.PlateOwners.Where(po => po.PlateID == id).ToList();
            ViewBag.Owners = owners;
            return View(forum);
        }

        [HttpGet]
        public ActionResult ShowForumPicture(int id)
        {
            var forum = db.Plates.Find(id);
            forum = db.Plates.Find(id);
            return File(forum.Picture, "image/jpg");
        }

        #endregion


        #region 主题管理

        /// <summary>
        ///  主题管理
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult Topic(string key, DateTime? Begin, DateTime? End,int? PlateID, int page = 1)
        {
            var plates = db.Plates.ToList();
            var query = db.Topics.AsEnumerable();
            if (!string.IsNullOrEmpty(key))
            {
                query = query.Where(t => t.Title.Contains(key));
            }
            if (Begin.HasValue)
            {
                query = query.Where(t => t.Time >= Begin);
            }
            if (End.HasValue)
            {
                query = query.Where(t => t.Time <= End);
            }
            if (PlateID.HasValue)
            {
                query = query.Where(t => t.PlateID == PlateID);
            }
            var topics = query.OrderByDescending(p => p.Time).ToPagedList(page, 20);
            ViewBag.Plates = plates;
            return View(topics);
        }

        /// <summary>
        /// 删除主题
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        [ValidateSID]
        public ActionResult TopicDelete(int id)
        {
            try
            {
                var topic = db.Topics.Find(id);
                db.Topics.Remove(topic);
                db.SaveChanges();
                return Content("ok");
            }
            catch
            {
                return Content("err");
            }
        }

        /// <summary>
        /// 详情展示
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult TopicShow(int id)
        {
            var topic = db.Topics.Find(id);
            return View(topic);
        }

        /// <summary>
        ///  设置是否显示
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [ValidateSID]
        [HttpGet]
        public ActionResult SetTopicShow(int id)
        {
            try
            {
                var topic = db.Topics.Find(id);
                if (topic.IsShow)
                {
                    topic.IsShow = false;
                }
                else if (!topic.IsShow)
                {
                    topic.IsShow = true;
                }
                db.SaveChanges();
                return Redirect("/Admin/Bbs/Topic");
            }
            catch
            {
                return Redirect("/Admin/Bbs/Message?msg=" + "主题设置显示状态失败！");
            }

        }

        /// <summary>
        /// 设置官方认证IsOfficeIdentified
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        [ValidateSID]
        public ActionResult SetTopicIdentify(int id)
        {
            try
            {
                var topic = db.Topics.Find(id);
                if (topic.IsOfficeIdentified)
                {
                    topic.IsOfficeIdentified = false;
                }
                else if (!topic.IsOfficeIdentified)
                {
                    topic.IsOfficeIdentified = true;
                }
                db.SaveChanges();
                return Redirect("/Admin/Bbs/Topic");
            }
            catch
            {
                return Redirect("/Admin/Bbs/Message?msg=" + "主题设置认证状态失败！");
            }
        }

        #endregion

        #region 版主管理
        [HttpGet]
        public ActionResult AddPlateOwner(int id)
        {
            var plate = db.Plates.Find(id);
            ViewBag.Plate = plate;
            return View();
        }

        /// <summary>
        /// 增加版主
        /// </summary>
        /// <param name="UserID"></param>
        /// <param name="pid"></param>
        /// <returns></returns>
        [ValidateAntiForgeryToken]
        [HttpPost]
        public ActionResult AddPlateOwner(int UserID, int pid)
        {
            var plate = db.Plates.Find(pid);
            ViewBag.Plate = plate;
            if (ModelState.IsValid)
            {
                try
                {
                    var owner = new PlateOwner();
                    owner.PlateID = pid;
                    owner.UserID = UserID;
                    db.PlateOwners.Add(owner);
                    db.SaveChanges();
                    return Redirect("/Admin/Bbs/ForumShow/" + pid);
                }
                catch (Exception ex)
                {
                    log.Error(new LogContent("设定版主出错", Helpers.HttpHelper.GetIPAddress()), ex);
                }
            }
            else
            {
                ModelState.AddModelError("", "信息填写错误！");
            }
            return View();
        }

        /// <summary>
        /// 删除版主
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [ValidateSID]
        [HttpPost]
        public ActionResult PlateOwnerDelete(int id)
        {
            try
            {
                var owner = db.PlateOwners.Find(id);
                db.PlateOwners.Remove(owner);
                db.SaveChanges();
            }
            catch (Exception ex)
            {
                log.Error(new LogContent("删除版主失败", Helpers.HttpHelper.GetIPAddress()), ex);
            }
            return Content("ok");
        } 
        #endregion
    }
}